<!-- 时空过滤器组件 -->
<template>
  <div class="spatial-temporal-filter">
    <!-- 空间过滤器 -->
    <div class="filter-section spatial-section">
      <div class="section-header">
        <el-icon class="header-icon"><Location /></el-icon>
        <span class="section-title">空间过滤</span>
        <el-switch
          v-model="spatialEnabled"
          class="enable-switch"
          @change="handleSpatialToggle"
        />
      </div>

      <div v-show="spatialEnabled" class="spatial-controls">
        <div class="map-tools">
          <el-button-group class="tool-group">
            <el-button
              :type="drawMode === 'rectangle' ? 'primary' : ''"
              size="small"
              @click="setDrawMode('rectangle')"
            >
              <el-icon><Crop /></el-icon>
              矩形选择
            </el-button>
            <el-button
              :type="drawMode === 'circle' ? 'primary' : ''"
              size="small"
              @click="setDrawMode('circle')"
            >
              <el-icon><Compass /></el-icon>
              圆形选择
            </el-button>
            <el-button
              :type="drawMode === 'polygon' ? 'primary' : ''"
              size="small"
              @click="setDrawMode('polygon')"
            >
              <el-icon><Grid /></el-icon>
              多边形选择
            </el-button>
          </el-button-group>
          
          <el-button size="small" @click="clearSpatialFilter">
            <el-icon><Delete /></el-icon>
            清除选区
          </el-button>
        </div>

        <!-- 预设区域 -->
        <div class="preset-areas">
          <el-select
            v-model="selectedPreset"
            placeholder="选择预设区域"
            size="small"
            @change="loadPresetArea"
          >
            <el-option
              v-for="area in presetAreas"
              :key="area.id"
              :label="area.name"
              :value="area.id"
            />
          </el-select>
        </div>

        <!-- 坐标信息 -->
        <div v-if="spatialFilter.coordinates.length > 0" class="coordinate-info">
          <div class="coord-header">选区坐标：</div>
          <div class="coord-details">
            <el-tag
              v-for="(coord, index) in spatialFilter.coordinates"
              :key="index"
              size="small"
              class="coord-tag"
            >
              {{ coord.lon.toFixed(4) }}, {{ coord.lat.toFixed(4) }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 时间过滤器 -->
    <div class="filter-section temporal-section">
      <div class="section-header">
        <el-icon class="header-icon"><Clock /></el-icon>
        <span class="section-title">时间过滤</span>
        <el-switch
          v-model="temporalEnabled"
          class="enable-switch"
          @change="handleTemporalToggle"
        />
      </div>

      <div v-show="temporalEnabled" class="temporal-controls">
        <!-- 时间模式选择 -->
        <div class="time-mode-tabs">
          <el-radio-group v-model="timeMode" size="small">
            <el-radio-button label="recent">最近时段</el-radio-button>
            <el-radio-button label="range">时间范围</el-radio-button>
            <el-radio-button label="custom">自定义</el-radio-button>
          </el-radio-group>
        </div>

        <!-- 最近时段 -->
        <div v-show="timeMode === 'recent'" class="recent-time">
          <el-select v-model="recentPeriod" @change="handleRecentChange">
            <el-option label="最近1小时" value="1h" />
            <el-option label="最近6小时" value="6h" />
            <el-option label="最近12小时" value="12h" />
            <el-option label="最近24小时" value="24h" />
            <el-option label="最近7天" value="7d" />
            <el-option label="最近30天" value="30d" />
          </el-select>
        </div>

        <!-- 时间范围 -->
        <div v-show="timeMode === 'range'" class="time-range">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleTimeRangeChange"
          />
        </div>

        <!-- 自定义时间轴 -->
        <div v-show="timeMode === 'custom'" class="custom-timeline">
          <div class="timeline-container">
            <div class="timeline-header">
              <span class="timeline-title">时间轴选择</span>
              <div class="timeline-controls">
                <el-button size="small" @click="zoomInTimeline">
                  <el-icon><ZoomIn /></el-icon>
                </el-button>
                <el-button size="small" @click="zoomOutTimeline">
                  <el-icon><ZoomOut /></el-icon>
                </el-button>
                <el-button size="small" @click="resetTimeline">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </div>
            
            <div class="timeline-slider">
              <el-slider
                v-model="customTimeRange"
                range
                :min="timelineMin"
                :max="timelineMax"
                :step="timelineStep"
                :format-tooltip="formatTimeTooltip"
                @change="handleCustomTimeChange"
              />
            </div>
            
            <div class="timeline-markers">
              <div class="marker start-marker">{{ formatTime(customTimeRange[0]) }}</div>
              <div class="marker end-marker">{{ formatTime(customTimeRange[1]) }}</div>
            </div>
          </div>
        </div>

        <!-- 时间统计 -->
        <div class="time-stats">
          <div class="stat-item">
            <span class="stat-label">时间范围：</span>
            <span class="stat-value">{{ getTimeRangeText() }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">数据量：</span>
            <span class="stat-value">{{ estimatedDataCount }} 条</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 过滤器操作 -->
    <div class="filter-actions">
      <el-button type="primary" @click="applyFilters">
        <el-icon><Filter /></el-icon>
        应用过滤
      </el-button>
      <el-button @click="resetFilters">
        <el-icon><Refresh /></el-icon>
        重置过滤器
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { 
  Location, Clock, Crop, Compass, Grid, Delete, 
  Filter, Refresh, ZoomIn, ZoomOut 
} from '@element-plus/icons-vue'

// 空间过滤
const spatialEnabled = ref(false)
const drawMode = ref('')
const selectedPreset = ref('')
const spatialFilter = reactive({
  type: '', // rectangle, circle, polygon
  coordinates: [],
  area: 0
})

// 预设区域
const presetAreas = ref([
  { id: 'beijing', name: '北京地区', coordinates: [[116.407526, 39.90403], [116.407526, 39.90403]] },
  { id: 'shanghai', name: '上海地区', coordinates: [[121.473701, 31.230416], [121.473701, 31.230416]] },
  { id: 'guangzhou', name: '广州地区', coordinates: [[113.264434, 23.129162], [113.264434, 23.129162]] },
  { id: 'shenzhen', name: '深圳地区', coordinates: [[114.085947, 22.547], [114.085947, 22.547]] }
])

// 时间过滤
const temporalEnabled = ref(false)
const timeMode = ref('recent')
const recentPeriod = ref('24h')
const timeRange = ref([])

// 自定义时间轴
const now = Date.now()
const timelineMin = ref(now - 30 * 24 * 60 * 60 * 1000) // 30天前
const timelineMax = ref(now)
const timelineStep = ref(60 * 60 * 1000) // 1小时步长
const customTimeRange = ref([now - 24 * 60 * 60 * 1000, now]) // 默认最近24小时

// 统计数据
const estimatedDataCount = ref(0)

// 事件定义
const emit = defineEmits(['spatial-change', 'temporal-change', 'filter-apply'])

// 计算属性
const getTimeRangeText = () => {
  if (!temporalEnabled.value) return '未启用'
  
  switch (timeMode.value) {
    case 'recent':
      return `最近${recentPeriod.value}`
    case 'range':
      return timeRange.value.length === 2 ? 
        `${timeRange.value[0]} 至 ${timeRange.value[1]}` : '未选择'
    case 'custom':
      return `${formatTime(customTimeRange.value[0])} 至 ${formatTime(customTimeRange.value[1])}`
    default:
      return '未知'
  }
}

// 空间过滤方法
const handleSpatialToggle = (enabled) => {
  if (!enabled) {
    clearSpatialFilter()
  }
  emit('spatial-change', { enabled, filter: spatialFilter })
}

const setDrawMode = (mode) => {
  drawMode.value = drawMode.value === mode ? '' : mode
  emit('spatial-change', { 
    enabled: spatialEnabled.value, 
    drawMode: drawMode.value,
    filter: spatialFilter 
  })
}

const clearSpatialFilter = () => {
  spatialFilter.type = ''
  spatialFilter.coordinates = []
  spatialFilter.area = 0
  drawMode.value = ''
  selectedPreset.value = ''
}

const loadPresetArea = (areaId) => {
  const area = presetAreas.value.find(a => a.id === areaId)
  if (area) {
    spatialFilter.type = 'preset'
    spatialFilter.coordinates = area.coordinates.map(coord => ({
      lon: coord[0],
      lat: coord[1]
    }))
    emit('spatial-change', { enabled: spatialEnabled.value, filter: spatialFilter })
  }
}

// 时间过滤方法
const handleTemporalToggle = (enabled) => {
  if (!enabled) {
    resetTimeFilters()
  }
  emit('temporal-change', { enabled, mode: timeMode.value, data: getCurrentTimeData() })
}

const handleRecentChange = (period) => {
  emit('temporal-change', { 
    enabled: temporalEnabled.value, 
    mode: 'recent', 
    period,
    data: getCurrentTimeData()
  })
  updateEstimatedCount()
}

const handleTimeRangeChange = (range) => {
  emit('temporal-change', { 
    enabled: temporalEnabled.value, 
    mode: 'range', 
    range,
    data: getCurrentTimeData()
  })
  updateEstimatedCount()
}

const handleCustomTimeChange = (range) => {
  emit('temporal-change', { 
    enabled: temporalEnabled.value, 
    mode: 'custom', 
    range: range.map(formatTime),
    data: getCurrentTimeData()
  })
  updateEstimatedCount()
}

const getCurrentTimeData = () => {
  switch (timeMode.value) {
    case 'recent':
      return { period: recentPeriod.value }
    case 'range':
      return { range: timeRange.value }
    case 'custom':
      return { range: customTimeRange.value.map(formatTime) }
    default:
      return {}
  }
}

const resetTimeFilters = () => {
  timeRange.value = []
  recentPeriod.value = '24h'
  customTimeRange.value = [now - 24 * 60 * 60 * 1000, now]
}

// 时间轴控制
const zoomInTimeline = () => {
  const range = timelineMax.value - timelineMin.value
  const center = (timelineMax.value + timelineMin.value) / 2
  const newRange = range * 0.5
  timelineMin.value = center - newRange / 2
  timelineMax.value = center + newRange / 2
  timelineStep.value = Math.max(timelineStep.value * 0.5, 60 * 1000) // 最小1分钟
}

const zoomOutTimeline = () => {
  const range = timelineMax.value - timelineMin.value
  const center = (timelineMax.value + timelineMin.value) / 2
  const newRange = Math.min(range * 2, 365 * 24 * 60 * 60 * 1000) // 最大1年
  timelineMin.value = center - newRange / 2
  timelineMax.value = center + newRange / 2
  timelineStep.value = Math.min(timelineStep.value * 2, 24 * 60 * 60 * 1000) // 最大1天
}

const resetTimeline = () => {
  timelineMin.value = now - 30 * 24 * 60 * 60 * 1000
  timelineMax.value = now
  timelineStep.value = 60 * 60 * 1000
  customTimeRange.value = [now - 24 * 60 * 60 * 1000, now]
}

// 工具方法
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatTimeTooltip = (value) => {
  return formatTime(value)
}

const updateEstimatedCount = () => {
  // 模拟数据量估算
  let baseCount = 10000
  
  if (temporalEnabled.value) {
    switch (timeMode.value) {
      case 'recent':
        const hours = recentPeriod.value.includes('h') ? 
          parseInt(recentPeriod.value) : 
          parseInt(recentPeriod.value) * 24
        baseCount = Math.floor(baseCount * hours / 24)
        break
      case 'range':
      case 'custom':
        baseCount = Math.floor(Math.random() * 50000) + 5000
        break
    }
  }
  
  if (spatialEnabled.value && spatialFilter.coordinates.length > 0) {
    baseCount = Math.floor(baseCount * 0.3) // 空间过滤通常会减少数据量
  }
  
  estimatedDataCount.value = baseCount
}

// 主要操作
const applyFilters = () => {
  const filters = {
    spatial: spatialEnabled.value ? {
      enabled: true,
      type: spatialFilter.type,
      coordinates: spatialFilter.coordinates,
      drawMode: drawMode.value
    } : { enabled: false },
    temporal: temporalEnabled.value ? {
      enabled: true,
      mode: timeMode.value,
      data: getCurrentTimeData()
    } : { enabled: false }
  }
  
  emit('filter-apply', filters)
}

const resetFilters = () => {
  spatialEnabled.value = false
  temporalEnabled.value = false
  clearSpatialFilter()
  resetTimeFilters()
  estimatedDataCount.value = 0
}

// 监听变化
watch([spatialEnabled, temporalEnabled], () => {
  updateEstimatedCount()
}, { immediate: true })
</script>

<style scoped>
.spatial-temporal-filter {
  background: rgba(31, 45, 61, 0.95);
  border-radius: 0.8vw;
  padding: 2vw;
  margin-bottom: 2vw;
}

.filter-section {
  margin-bottom: 2vh;
  padding-bottom: 2vh;
  border-bottom: 1px solid #2d3a4b;
}

.filter-section:last-of-type {
  border-bottom: none;
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 1.5vh;
  gap: 1vw;
}

.header-icon {
  color: #409EFF;
  font-size: 1.2vw;
}

.section-title {
  color: #bfcbd9;
  font-size: 1.1vw;
  font-weight: bold;
  flex: 1;
}

.enable-switch {
  margin-left: auto;
}

.spatial-controls,
.temporal-controls {
  padding-left: 2.2vw;
}

.map-tools {
  display: flex;
  gap: 1vw;
  margin-bottom: 1.5vh;
  align-items: center;
}

.tool-group {
  flex: 1;
}

.preset-areas {
  margin-bottom: 1.5vh;
}

.coordinate-info {
  background: rgba(45, 58, 75, 0.6);
  border-radius: 0.6vw;
  padding: 1vh 1.5vw;
  border: 1px solid #2d3a4b;
}

.coord-header {
  color: #bfcbd9;
  font-size: 0.9vw;
  margin-bottom: 0.8vh;
}

.coord-details {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5vw;
}

.coord-tag {
  background: rgba(64, 158, 255, 0.2);
  border-color: #409EFF;
  color: #409EFF;
  font-size: 0.8vw;
}

.time-mode-tabs {
  margin-bottom: 1.5vh;
}

.recent-time,
.time-range {
  margin-bottom: 1.5vh;
}

.custom-timeline {
  background: rgba(45, 58, 75, 0.6);
  border-radius: 0.6vw;
  padding: 1.5vh 1.5vw;
  border: 1px solid #2d3a4b;
  margin-bottom: 1.5vh;
}

.timeline-container {
  width: 100%;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1vh;
}

.timeline-title {
  color: #bfcbd9;
  font-size: 0.9vw;
}

.timeline-controls {
  display: flex;
  gap: 0.5vw;
}

.timeline-slider {
  margin: 2vh 0;
}

.timeline-markers {
  display: flex;
  justify-content: space-between;
  margin-top: 1vh;
}

.marker {
  color: #8591a3;
  font-size: 0.8vw;
}

.time-stats {
  background: rgba(45, 58, 75, 0.6);
  border-radius: 0.6vw;
  padding: 1vh 1.5vw;
  border: 1px solid #2d3a4b;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5vh;
}

.stat-item:last-child {
  margin-bottom: 0;
}

.stat-label {
  color: #8591a3;
  font-size: 0.9vw;
}

.stat-value {
  color: #bfcbd9;
  font-size: 0.9vw;
  font-weight: bold;
}

.filter-actions {
  display: flex;
  gap: 1vw;
  justify-content: center;
  margin-top: 2vh;
}

:deep(.el-input__inner) {
  background: rgba(45, 58, 75, 0.8) !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

:deep(.el-input__inner:focus) {
  border-color: #409EFF !important;
}

:deep(.el-input__inner::placeholder) {
  color: #8591a3 !important;
}

:deep(.el-select .el-input__inner) {
  background: rgba(45, 58, 75, 0.8) !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

:deep(.el-select-dropdown) {
  background: rgba(38, 52, 69, 0.95) !important;
  border-color: #2d3a4b !important;
}

:deep(.el-select-dropdown__item) {
  background: transparent !important;
  color: #bfcbd9 !important;
}

:deep(.el-select-dropdown__item:hover) {
  background: rgba(64, 158, 255, 0.2) !important;
  color: #409EFF !important;
}

:deep(.el-select-dropdown__item.selected) {
  background: #409EFF !important;
  color: #ffffff !important;
}

:deep(.el-date-editor.el-input) {
  background: rgba(45, 58, 75, 0.8) !important;
  border-color: #2d3a4b !important;
}

:deep(.el-date-editor.el-input .el-input__inner) {
  background: transparent !important;
  color: #bfcbd9 !important;
}

:deep(.el-picker-panel) {
  background: rgba(38, 52, 69, 0.95) !important;
  border-color: #2d3a4b !important;
}

:deep(.el-button) {
  border-radius: 0.6vw;
  font-size: 1vw;
  padding: 1vh 2vw;
}

:deep(.el-switch__core) {
  background: #2d3a4b;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background: #409EFF;
}

:deep(.el-radio-button__inner) {
  background: transparent;
  border-color: #2d3a4b;
  color: #bfcbd9;
  font-size: 0.9vw;
}

:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background: #409EFF;
  border-color: #409EFF;
  color: #ffffff;
}

:deep(.el-slider__runway) {
  background: #2d3a4b;
}

:deep(.el-slider__bar) {
  background: #409EFF;
}

:deep(.el-slider__button) {
  border-color: #409EFF;
}
</style>